<!--
* description: 维修工时标准设置
* author: xuliwen
* createdDate: 2021-01-29
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :dynamic-api-style="'restful'"
      :callback-obj="callbackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
    <!-- 车型工时弹窗 -->
    <technicianEdit
      :key="technicianEditKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="technicianEditVisible"
      @sendCodeClose="sendCodeClose"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import request from '@/utils/request'
import api from '@/api/se/apiBaseData'
import Vue from 'vue'

export default {
  name: 'MaintenanceHoursSetting',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit'),
    technicianEdit: () => import('./technicianEdit.vue')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      technicianEditVisible: false,
      technicianEditKey: 'technicianEditKey',
      editRowData: {},
      // 网格查询API配置对象
      // api配置
      apiConfig: api.queryWorkingHoursStandard,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'add',
          clickEvent: this.add,
          text: this.$t('sys.button.add'), // 新增
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          name: 'importTemplate',
          position: 'upload',
          clickEvent: () => this.handFileListChange(),
          text: '导入'
        },
        {
          compKey: 'btnKey5',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          click: (event) => {
            this.templateDownload()
            // this.export(
            //   // api.templateDownload.APIUrl,
            //   "质量跟踪特殊件查询模板",
            //   { dataType: "excel" }
            // );
          }
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // {
            //   compKey: 'compKey1',
            //   labelName: '工时来源：',
            //   codeField: 'wiKey',
            //   component: () => import('@/components/org/commonInput'),
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: true
            // },
            {
              compKey: 'compKey2',
              labelName: '维修大类：',
              codeField: 'operatePartCode',
              textField: 'opratePartName',
              change: this.getSmallClass,
              // customObj: {
              //   api: api.findOpratePlace,
              //   defOptionFields:['operatePartCode','opratePartName']
              // },
              component: () => import('@/components/wms/dropdownList/dropdownList'),
              options: [],
              // component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '维修小类：',
              codeField: 'rrpairSmallKindCode',
              textField: 'rrpairSmallKindName',
              disabled: true,
              component: () => import('@/components/wms/dropdownList/dropdownList'),
              options: [],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '工时编码：',
              codeField: 'wiCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '维修内容：',
              codeField: 'repairContent',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '状态：',
              codeField: 'isEnable',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '启用' },
                { statusId: '0', statusText: '禁用' }
              ],
              type: 'dropdownList',

              isMul: false,
              isMust: false
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'wiId',
              label: '工时ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'rrpairSmallKindCode',
              label: '维修小类code',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'opratePartCode',
              label: '维修大类code',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn1',
              label: '操作',
              minWidth: 180,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '修改',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                },
                {
                  compKey: 'propKey2',
                  labelName: '删除',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.delet(index)
                },
                {
                  compKey: 'propKey3',
                  labelName: '车型工时',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.carList(index)
                }
              ]
            },
            {
              prop: 'wiCode',
              label: '工时编码'
            },
            {
              prop: 'repairContent',
              label: '维修内容'
            },
            // {
            //   prop: 'wiKey',
            //   label: '工时来源'
            // },
            {
              prop: 'isEnableCn',
              label: '状态'
            },
            {
              prop: 'wiMaxSaleQty',
              label: '工时'
            },
            {
              prop: 'opratePartName',
              label: '维修大类'
            },
            {
              prop: 'rrpairSmallKindName',
              label: '维修小类'
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],
      callbackObj: {
        // 双击车型弹窗
        onRowDbClick: (row, column, event, rowIndex) => {
          this.editRowData = row
          this.oppentechnicianEdit()
        }
      },
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          wiKey: '',
          operatePartCode: '',
          rrpairSmallKindCode: '',
          wiCode: '',
          repairContent: '',
          isEnable: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },
  watch: {
    'formField.operatePartCode': {
      handler: function(val, oldval) {
        if (val == null || val == '' || val == undefined) {
          this.tableComponents[1].disabled = true
        }
      }
    }
  },
  mounted() {
    this.getOperatePart()
  },
  methods: {
    getOperatePart() {
      request({
        url: api.findOpratePlace.APIUrl,
        method: 'post',
        data: {}
      }).then((res) => {
        res.rows.map((item) => {
          this.tableComponents[0].options.push({
            label: item.opratePartName,
            value: item.operatePartCode
          })
        })
      })
    },
    getrrpairSmallKind(val) {
      if (val != '' && val != null && val != undefined) {
        this.tableComponents[1].options = []
        this.tableComponents[1].disabled = false
        request({
          url: api.findSmallOpratePlace.APIUrl,
          method: 'post',
          data: { operatePartCode: val }
        }).then((res) => {
          res.rows.map((item) => {
            this.tableComponents[1].options.push({
              label: item.rrpairSmallKindName,
              value: item.rrpairSmallKindCode
            })
          })
        })
      }
    },
    getSmallClass(val) {
      this.formField.rrpairSmallKindCode = ''
      if (val == null || val == '' || val == undefined) {
        this.tableComponents[2].disabled = true
      } else {
        this.tableComponents[2].disabled = false
        this.getrrpairSmallKind(val)
      }
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('维修工时标准设置.xlsx')
      this.$requestAPI({
        apiUrl: api.importWorkingHoursDownload.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url = api.importWorkingHoursStandard.APIUrl
      that
        .$requestUpload(url, param)
        .then(response => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTable()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
    },
    // 车型工时弹窗
    sendCodeClose() {
      this.technicianEditVisible = false
      this.technicianEditKey += '1'
    },
    // 双击车型工时弹窗
    oppentechnicianEdit() {
      this.technicianEditVisible = true
    },
    // 车型弹窗
    carList(index) {
      this.technicianEditVisible = true
      this.editRowData = this.$utils.deepCopy(
        this.$refs['multipleTable'].list[index]
      )
    },
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(
        this.$refs['multipleTable'].list[index]
      )
    },
    // 删除
    delet(index) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.editRowData = this.$refs['multipleTable'].list[index]
        const that = this
        const queryObj = {
        // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: api.deleteWorkingHoursStandard,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: this.editRowData
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then((response) => {
          console.log(response)
          if (response.result === '1') {
            this.$message({
              message: response.msg /* 保存成功*/,
              type: 'success',
              duration: 1000
            })
            this.queryTable(1)
          } else {
          // 保存失败
            this.$message({
              message: response.msg,
              type: 'warn',
              duration: 1000
            })
          }
        })
      })
    }
  }
}
</script>
